//
//  SLOauthViewController.swift
//  0319iOSweiboDemo
//
//  Created by Tang on 16/3/21.
//  Copyright © 2016年 大天朝. All rights reserved.
//

import UIKit
import SVProgressHUD

class SLOauthViewController: UIViewController {
    
    override func loadView() {
        view = webView
        
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        //没有背景颜色.在Modal只看的到导航栏
       view.backgroundColor = UIColor.whiteColor()
        
        //设置导航栏
        setupNavgationBar()
        
        title = "新浪微博"
        
        //加载授权登录界面
        let request = NSURLRequest(URL: SLNetworkTool.sharedInstance.oAuthURL())
        webView.loadRequest(request)
        
        // 弹出正在加载的提示
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Black)
        
    }
    
    //MARK: - UIWebView代理方法
    /// 是否加载某个URL,return true表示加载, return false不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
//        print("urlString: \(urlString)")
        
        // 如果加载的不是授权回调页面,直接加载网页,
        // 如果加载的是授权回调页面,对后面的参数进行判断,如果有code=表示点击了授权按钮,否则点击取消
        
        //点击取消: "http://www.weibo.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330"
        
        //点击授权: "http://www.weibo.com/?code=75edf5bb49bf680e2a1d82520aab4153"
        
        //判断是否回调地址
        if !urlString!.hasPrefix(SLNetworkTool.sharedInstance.redierct_url) {
       
            return true
        } else {
//             print("回调地址: \(request.URL?.query)")
            //回调地址: Optional("code=fb3922e117a1593c696485729ce6b48b")
            
            //判断后面是否跟有参数
            if let query = request.URL?.query {
                let nsQuery = query as NSString
                let codeString = "code="
                //判断query里面是否包含code=字符串
                if nsQuery.hasPrefix(codeString) { //授权
                    let code = nsQuery.substringFromIndex(codeString.characters.count)
                    
                    //AFN加载 
                    //3.调用闭包
                    SLUserAccountViewModel.sharedInstance.loadAccessToken(code, completion: { (error) -> () in
                        //判断是否有错
                        if error != nil {
                            SLPrint("error: \(error)")
                            SVProgressHUD.showErrorWithStatus("获取AccessToken失败")
                            
                            //延迟1秒关闭
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                                self.close()
                            })
                            return
                        }
                        
                        //                    print("code: \(code)")
                        //没有错误,关闭控制器
                        self.close()
                        
                        //切换控制器
                        //                   let appDelagate = UIApplication.sharedApplication().delegate as? AppDelegate
                        //                    appDelagate?.switchRootViewController(SLWelocomeViewController())
                        AppDelegate.outSwitchRootViewController(SLWelocomeViewController())
                    })
                    
                } else { //点击取消
                    close()  //关闭界面
                }
                
            }
        
        return false
        }
    }
    
     //设置导航栏
    private func setupNavgationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
    }
    
    //MARK: - 点击方法
    //填充
    @objc private func autoFill() {
        let jsCode = "document.getElementById('userId').value='18229306678';document.getElementById('passwd').value='l136504174'"
        //document.getElementById('userId').value='18229306678'
        //document.getElementById('passwd').value='l136504174'
   
        //执行js代码
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    //关闭控制器  取消
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    //MARK: - 懒加载webView  
    //三种方式
//    private lazy var webView : UIWebView = {
//        let webView = UIWebView()
//        return webView
//    }()
    private lazy var webView = UIWebView()
    //private lazy var webView : UIWebView = UIWebView()
    
}
//MARK: - 扩展当前SLOauthViewController 实现 UIWebViewDelegate
extension SLOauthViewController : UIWebViewDelegate {
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭提示
        SVProgressHUD.dismiss()
    }
}
